import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getSession } from '@/utils/sessionManager'

export const useSessionStore = defineStore('session', () => {
  const isSessionReady = ref(false)
  const sessionPromise = ref<Promise<void> | null>(null)

  const initSession = async () => {
    if (sessionPromise.value) {
      return sessionPromise.value
    }
    // 清空缓存sessionID
    localStorage.removeItem('sessionId')
    sessionPromise.value = getSession().then((res:any) => {
      if (res && res.code === 200) {
        localStorage.setItem("sessionId", res.data);
      }
      isSessionReady.value = true
      console.log('Session initialized successfully')
    }).catch((error) => {
      console.error('Session initialization failed:', error)
      throw error
    })

    return sessionPromise.value
  }

  const waitForSession = async () => {
    if (isSessionReady.value) {
      return Promise.resolve()
    }
    
    if (sessionPromise.value) {
      return sessionPromise.value
    }
    
    return initSession()
  }

  return {
    isSessionReady,
    initSession,
    waitForSession
  }
}) 